package cn.iocoder.yudao.module.product.service.sku;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.CurrentMarkStatusEnum;
import cn.iocoder.yudao.framework.common.util.CheckUtils;
import cn.iocoder.yudao.framework.common.util.CollectionUtil;
import cn.iocoder.yudao.framework.common.util.constant.ConstantUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.infra.api.code.AutoCodeUtilsApi;
import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuUpdateStockReqDTO;
import cn.iocoder.yudao.module.product.controller.admin.sku.vo.ProductSkuBaseVO;
import cn.iocoder.yudao.module.product.controller.admin.sku.vo.ProductSkuCreateOrUpdateReqVO;
import cn.iocoder.yudao.module.product.controller.admin.sku.vo.ProductSkuRespVO;
import cn.iocoder.yudao.module.product.controller.admin.skuofferpricerelation.vo.SkuOfferPriceRelationSaveReqVO;
import cn.iocoder.yudao.module.product.controller.admin.skustorerelation.vo.SkuStoreRelationSaveReqVO;
import cn.iocoder.yudao.module.product.controller.admin.stockinfo.vo.StockInfoSaveReqVO;
import cn.iocoder.yudao.module.product.convert.sku.ProductSkuConvert;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyDO;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyValueDO;
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
import cn.iocoder.yudao.module.product.dal.dataobject.skuofferpricerelation.SkuOfferPriceRelationDO;
import cn.iocoder.yudao.module.product.dal.dataobject.skustorerelation.SkuStoreRelationDO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.dal.mysql.sku.ProductSkuMapper;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyService;
import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
import cn.iocoder.yudao.module.product.service.skuofferpricerelation.SkuOfferPriceRelationService;
import cn.iocoder.yudao.module.product.service.skustorerelation.SkuStoreRelationService;
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
import cn.iocoder.yudao.module.product.service.stockinfo.StockInfoService;
import cn.iocoder.yudao.module.product.utils.UserUtils;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.trade.api.store.TradeStoreApi;
import cn.iocoder.yudao.module.trade.api.store.dto.DeliveryPickUpStoreDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.*;

/**
 * 商品 SKU Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ProductSkuServiceImpl implements ProductSkuService {

    @Resource
    private ProductSkuMapper productSkuMapper;

    @Resource
    @Lazy // 循环依赖，避免报错
    private ProductSpuService productSpuService;
    @Resource
    @Lazy // 循环依赖，避免报错
    private ProductPropertyService productPropertyService;
    @Resource
    private ProductPropertyValueService productPropertyValueService;
    @Resource
    private SkuOfferPriceRelationService skuOfferPriceRelationService;
    @Resource
    private SkuStoreRelationService skuStoreRelationService;
    @Resource
    private TradeStoreApi tradeStoreApi;
    @Resource
    private AutoCodeUtilsApi autoCodeUtilsApi;
    @Resource
    private UserUtils userUtils;
    @Resource
    private StockInfoService stockInfoService;

    @Override
    public void deleteSku(Long id) {
        // 校验存在
        validateSkuExists(id);
        // 删除
        productSkuMapper.deleteById(id);
    }

    private void validateSkuExists(Long id) {
        if (productSkuMapper.selectById(id) == null) {
            throw exception(SKU_NOT_EXISTS);
        }
    }

    @Override
    public ProductSkuDO getSku(Long id) {
        return productSkuMapper.selectById(id);
    }

    @Override
    public List<ProductSkuDO> getSkuList() {
        // 只查询商品 过滤掉包装物
        LambdaQueryWrapper<ProductSkuDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSkuDO ::getProductType, 0);
        return productSkuMapper.selectList(queryWrapper);
    }

    @Override
    public List<ProductSkuDO> getSkuList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return productSkuMapper.selectBatchIds(ids);
    }

    @Override
    public void validateSkuList(List<ProductSkuCreateOrUpdateReqVO> skus, Boolean specType) {
        // 0、校验skus是否为空
        if (CollUtil.isEmpty(skus)) {
            throw exception(SKU_NOT_EXISTS);
        }
        // 单规格，赋予单规格默认属性
        if (ObjectUtil.equal(specType, false)) {
            ProductSkuCreateOrUpdateReqVO skuVO = skus.get(0);
            List<ProductSkuBaseVO.Property> properties = new ArrayList<>();
            ProductSkuBaseVO.Property property = new ProductSkuBaseVO.Property();
            property.setPropertyId(ProductPropertyDO.ID_DEFAULT);
            property.setPropertyName(ProductPropertyDO.NAME_DEFAULT);
            property.setValueId(ProductPropertyValueDO.ID_DEFAULT);
            property.setValueName(ProductPropertyValueDO.NAME_DEFAULT);
            properties.add(property);
            skuVO.setProperties(properties);
            return; // 单规格不需要后续的校验
        }

        // 1、校验属性项存在
        Set<Long> propertyIds = skus.stream().filter(p -> p.getProperties() != null)
                // 遍历多个 Property 属性
                .flatMap(p -> p.getProperties().stream())
                // 将每个 Property 转换成对应的 propertyId，最后形成集合
                .map(ProductSkuCreateOrUpdateReqVO.Property::getPropertyId)
                .collect(Collectors.toSet());
        List<ProductPropertyDO> propertyList = productPropertyService.getPropertyList(propertyIds);
        if (propertyList.size() != propertyIds.size()) {
            throw exception(PROPERTY_NOT_EXISTS);
        }

        // 2. 校验，一个 SKU 下，没有重复的属性。校验方式是，遍历每个 SKU ，看看是否有重复的属性 propertyId
        Map<Long, ProductPropertyValueDO> propertyValueMap = convertMap(productPropertyValueService.getPropertyValueListByPropertyId(propertyIds), ProductPropertyValueDO::getId);
        skus.forEach(sku -> {
            Set<Long> skuPropertyIds = convertSet(sku.getProperties(), propertyItem -> propertyValueMap.get(propertyItem.getValueId()).getPropertyId());
            if (skuPropertyIds.size() != sku.getProperties().size()) {
                throw exception(SKU_PROPERTIES_DUPLICATED);
            }
        });

        // 3. 再校验，每个 Sku 的属性值的数量，是一致的。
        int attrValueIdsSize = skus.get(0).getProperties().size();
        for (int i = 1; i < skus.size(); i++) {
            if (attrValueIdsSize != skus.get(i).getProperties().size()) {
                throw exception(SPU_ATTR_NUMBERS_MUST_BE_EQUALS);
            }
        }

        // 4. 最后校验，每个 Sku 之间不是重复的
        // 每个元素，都是一个 Sku 的 attrValueId 集合。这样，通过最外层的 Set ，判断是否有重复的.
        Set<Set<Long>> skuAttrValues = new HashSet<>();
        for (ProductSkuCreateOrUpdateReqVO sku : skus) {
            // 添加失败，说明重复
            if (!skuAttrValues.add(convertSet(sku.getProperties(), ProductSkuCreateOrUpdateReqVO.Property::getValueId))) {
                throw exception(SPU_SKU_NOT_DUPLICATE);
            }
        }
    }

    @Override
    public void createSkuList(Long spuId, List<ProductSkuCreateOrUpdateReqVO> skuCreateReqList, String spuCode, List<Long> nearStroeIds) {
//        productSkuMapper.insertBatch(ProductSkuConvert.INSTANCE.convertList06(skuCreateReqList, spuId));
        skuCreateReqList.forEach(productSkuCreateOrUpdateReqVO -> {
            ProductSkuDO productSkuDO = ProductSkuConvert.INSTANCE.convertProductSkuDO(productSkuCreateOrUpdateReqVO, spuId);
            String code =autoCodeUtilsApi.getSpuAndSkuCode(spuCode);
            productSkuDO.setSkuCode(ConstantUtil.SKU+spuCode+code);

            //获取当前用户
            AdminUserRespDTO adminUserRespDTO = userUtils.getUser();
            if(Objects.nonNull(adminUserRespDTO)){
                productSkuDO.setCreator(adminUserRespDTO.getUsername());
            }

            productSkuMapper.insert(productSkuDO);

            // 插入门店信息到库存表中
            if (!CollectionUtil.isEmpty(nearStroeIds)) {
                List<StockInfoSaveReqVO> list = new ArrayList<>();
                nearStroeIds.forEach(x -> {
                    StockInfoSaveReqVO reqVO = new StockInfoSaveReqVO();
                    reqVO.setSkuId(productSkuDO.getId());
                    reqVO.setOwnerId(x);
                    reqVO.setOwnerType(1);
                    reqVO.setSpuId(spuId);

                });
                stockInfoService.createStockInfoBath(list);
            }

            //插入 sku和统一定价关系表   （新增是否使用容器 是否退残业务）
            createSkuOfferPriceRelation(productSkuDO.getId(),productSkuCreateOrUpdateReqVO);
        });
    }

    /**
     * 新增商品和统一定价关系表 （新增是否使用容器 是否退残业务）
     * @param: ProductSkuCreateOrUpdateReqVO  商品信息
     * @param: id 商品id
     * @return: void
     * @author xulimin
     * @date: 2023/12/26 15:40
     */
    private void createSkuOfferPriceRelation(Long id, ProductSkuCreateOrUpdateReqVO productSkuCreateOrUpdateReqVO) {
        SkuOfferPriceRelationSaveReqVO skuOfferPriceRelationSaveReqVO =new SkuOfferPriceRelationSaveReqVO();
        skuOfferPriceRelationSaveReqVO.setPrice(productSkuCreateOrUpdateReqVO.getPrice());
        skuOfferPriceRelationSaveReqVO.setIncompletePrice(productSkuCreateOrUpdateReqVO.getIncompletePrice());
        skuOfferPriceRelationSaveReqVO.setEnable(productSkuCreateOrUpdateReqVO.getEnable() != null ? productSkuCreateOrUpdateReqVO.getEnable():false);
        skuOfferPriceRelationSaveReqVO.setEffective(Boolean.FALSE);
        skuOfferPriceRelationSaveReqVO.setCurrentMark(CurrentMarkStatusEnum.CURR.getStatus());
        skuOfferPriceRelationSaveReqVO.setSkuId(id);
        skuOfferPriceRelationService.createSkuOfferPrice(skuOfferPriceRelationSaveReqVO);
    }



    @Override
    public List<ProductSkuDO> getSkuListBySpuId(Long spuId) {
        return productSkuMapper.selectListBySpuId(spuId);
    }

    @Override
    public List<ProductSkuDO> getSkuListBySpuId(Collection<Long> spuIds) {
        if (CollUtil.isEmpty(spuIds)) {
            return Collections.emptyList();
        }
        return productSkuMapper.selectListBySpuId(spuIds);
    }

    @Override
    public void deleteSkuBySpuId(Long spuId) {
        productSkuMapper.deleteBySpuId(spuId);
    }

    @Override
    public List<ProductSkuDO> getSkuListByAlarmStock() {
        return productSkuMapper.selectListByAlarmStock();
    }

    @Override
    public int updateSkuProperty(Long propertyId, String propertyName) {
        // 获取所有的 sku
        List<ProductSkuDO> skuDOList = productSkuMapper.selectList();
        // 处理后需要更新的 sku
        List<ProductSkuDO> updateSkus = new ArrayList<>();
        if (CollUtil.isEmpty(skuDOList)) {
            return 0;
        }
        skuDOList.stream().filter(sku -> sku.getProperties() != null)
                .forEach(sku -> sku.getProperties().forEach(property -> {
                    if (property.getPropertyId().equals(propertyId)) {
                        property.setPropertyName(propertyName);
                        updateSkus.add(sku);
                    }
                }));
        if (CollUtil.isEmpty(updateSkus)) {
            return 0;
        }

        productSkuMapper.updateBatch(updateSkus);
        return updateSkus.size();
    }

    @Override
    public int updateSkuPropertyValue(Long propertyValueId, String propertyValueName) {
        // 获取所有的 sku
        List<ProductSkuDO> skuDOList = productSkuMapper.selectList();
        // 处理后需要更新的 sku
        List<ProductSkuDO> updateSkus = new ArrayList<>();
        if (CollUtil.isEmpty(skuDOList)) {
            return 0;
        }
        skuDOList.stream()
                .filter(sku -> sku.getProperties() != null)
                .forEach(sku -> sku.getProperties().forEach(property -> {
                    if (property.getValueId().equals(propertyValueId)) {
                        property.setValueName(propertyValueName);
                        updateSkus.add(sku);
                    }
                }));
        if (CollUtil.isEmpty(updateSkus)) {
            return 0;
        }

        productSkuMapper.updateBatch(updateSkus);
        return updateSkus.size();
    }

    @Override
    public List<ProductSkuDO> selectBySpuIdList(Long id) {
        LambdaQueryWrapperX<ProductSkuDO> sku = new LambdaQueryWrapperX<>();
        sku.eq(ProductSkuDO :: getSpuId, id);
        return productSkuMapper.selectList(sku);
//        return productSkuMapper.selectBySpuIdList(id); TODO 不使用sql 避免properties json串不能映射成数组
    }

    @Override
    public List<ProductSkuRespVO> findSkuListBySpuId(Long spuId) {
        List<ProductSkuRespVO> productSkuRespVOList = ProductSkuConvert.INSTANCE.convertList(productSkuMapper.selectListBySpuId(spuId));
        productSkuRespVOList.forEach(productSkuRespVO -> {
            //门店价格计算
            Integer storePrice =countStorePrice(productSkuRespVO.getPrice(),productSkuRespVO.getId());
            productSkuRespVO.setStorePrice(storePrice);

            //门店名称
            String storeName = getStoreNameBySkuId(productSkuRespVO.getId());
            productSkuRespVO.setStoreName(storeName);

            //统一定价
            SkuOfferPriceRelationDO skuOfferPriceRelationDO = skuOfferPriceRelationService.getSkuOfferPriceRelationBySkuId(productSkuRespVO.getId());
            if(ObjectUtil.isNotEmpty(skuOfferPriceRelationDO)){
                productSkuRespVO.setPrice(skuOfferPriceRelationDO.getPrice());
                productSkuRespVO.setEnable(skuOfferPriceRelationDO.getEnable());
                productSkuRespVO.setIncompletePrice(skuOfferPriceRelationDO.getIncompletePrice());
            }

            //查询容器名称
            if(null != productSkuRespVO.getContainerSkuId()){
                ProductSkuDO productSkuDO =  productSkuMapper.selectOne(ProductSkuDO::getId,productSkuRespVO.getContainerSkuId());
                if(Objects.nonNull(productSkuDO)){
                    ProductSpuDO productSpuDO = productSpuService.getSpu(productSkuDO.getSpuId());
                    productSkuRespVO.setContainerSpec(productSpuDO.getName());
                }
                //需要容器
                productSkuRespVO.setIsUseContainer(CommonStatusEnum.DISABLE.getStatus());
            }else {
                //不需要容器
                productSkuRespVO.setIsUseContainer(CommonStatusEnum.ENABLE.getStatus());
            }
        });
        return productSkuRespVOList;
    }

    @Override
    public List<ProductSkuRespVO> getContainerList() {
        LambdaQueryWrapperX<ProductSkuDO> lambdaQueryWrapper = new LambdaQueryWrapperX<>();
        lambdaQueryWrapper.eq(ProductSkuDO::getProductType,1);
        lambdaQueryWrapper.eq(ProductSkuDO::getDeleted,false);
        List<ProductSkuRespVO> productSkuRespVOList = ProductSkuConvert.INSTANCE.convertList(productSkuMapper.selectList(lambdaQueryWrapper));
        if(CollUtil.isNotEmpty(productSkuRespVOList)){
            productSkuRespVOList.forEach(productSkuRespVO -> {
                ProductSpuDO productSpuDO = productSpuService.getSpu(productSkuRespVO.getSpuId());
                productSkuRespVO.setContainerSpec(productSpuDO.getName());
            });
        }

        return productSkuRespVOList;
    }

    @Override
    public void updateSkuById(Long skuId, Integer price) {
        LambdaUpdateWrapper<ProductSkuDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ProductSkuDO::getId,skuId);
        lambdaUpdateWrapper.set(ProductSkuDO::getPrice,price);
        productSkuMapper.update(lambdaUpdateWrapper);
    }


    /**
     * 获取门店名称
     * @param: id 商品id
     * @return: string
     * @author xulimin
     * @date: 2023/12/27 11:27
     */
    private String getStoreNameBySkuId(Long id) {
        String storeName = "";
        List<SkuStoreRelationDO> skuStoreRelationDOList = skuStoreRelationService.getSkuStoreRelationBySkuId(id);
        if(CollUtil.isEmpty(skuStoreRelationDOList)){
           return storeName;
        }
        List<Long> storeId = skuStoreRelationDOList.stream().map(SkuStoreRelationDO::getPickUpStoreId).collect(Collectors.toList());
        //查询门店
        List<DeliveryPickUpStoreDTO> storeDTOList = tradeStoreApi.getStoreList(storeId);

        if(CollUtil.isEmpty(storeDTOList)){
            return storeName;
        }
        List<String> name = storeDTOList.stream().map(DeliveryPickUpStoreDTO::getName).collect(Collectors.toList());
        return String.join(",",name);
    }


    /**
     * 计算门店价格
     * @param: id 商品id
     * @return: Integer
     * @author xulimin
     * @date: 2023/12/27 10:53
     */
    private Integer countStorePrice(Integer price, Long id) {
        BigDecimal storePrice = new BigDecimal(price);
        List<SkuStoreRelationDO> skuStoreRelationDOList = skuStoreRelationService.getSkuStoreRelationBySkuId(id);
        if(CollUtil.isNotEmpty(skuStoreRelationDOList)){
            for (SkuStoreRelationDO skuStoreRelationDO:skuStoreRelationDOList) {
                if(CheckUtils.isEmpty(skuStoreRelationDO.getType()) || CheckUtils.isEmpty(skuStoreRelationDO.getFluctuationPrice())){
                    return storePrice.intValue();
                }
                if(CommonStatusEnum.ENABLE.getStatus().equals(skuStoreRelationDO.getType())){
                    storePrice = storePrice.add(BigDecimal.valueOf(skuStoreRelationDO.getFluctuationPrice()));
                }else {
                    storePrice = storePrice.subtract(BigDecimal.valueOf(skuStoreRelationDO.getFluctuationPrice()));
                }
            }
        }

        return storePrice.intValue();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSkuList(Long spuId, List<ProductSkuCreateOrUpdateReqVO> skus, List<Long> nearStroeIds) {
        // 构建属性与 SKU 的映射关系;
        Map<String, Long> existsSkuMap = convertMap(ProductSkuConvert.INSTANCE.convertListVO(productSkuMapper.selectListBySpuId(spuId)),
                ProductSkuConvert.INSTANCE::buildPropertyKey, ProductSkuCreateOrUpdateReqVO::getId);

        // 拆分三个集合，新插入的、需要更新的、需要删除的
        List<ProductSkuCreateOrUpdateReqVO> insertSkus = new ArrayList<>();
        List<ProductSkuCreateOrUpdateReqVO> updateSkus = new ArrayList<>();
        skus.forEach(sku -> {
            String propertiesKey = ProductSkuConvert.INSTANCE.buildPropertyKey(sku);
            // 1、找得到的，进行更新
            Long existsSkuId = existsSkuMap.remove(propertiesKey);
            if (existsSkuId != null) {
                sku.setId(existsSkuId);
                updateSkus.add(sku);
                return;
            }
            // 2、找不到，进行插入
            sku.setSpuId(spuId);
            insertSkus.add(sku);
        });

        // 校验是否更改门店
        List<StockInfoSaveReqVO> store = stockInfoService.getStockInfoBySpuId(spuId);
        //商品所在的门店
        List<Long> storeAllIds = store.stream().map(StockInfoSaveReqVO::getOwnerId).collect(Collectors.toList());

//        List<Long> collect2 = collect1.stream().filter(x -> !nearStroeIds.contains(x)).collect(Collectors.toList());


        // 如果不为空 则需要修改对应门店 删除对应数据
        if (CollectionUtils.isNotEmpty(nearStroeIds) && CollectionUtils.isNotEmpty(storeAllIds)) {
            // 判断是新增还是修改
//            if (nearStroeIds.size() <= storeAllIds.size()) {
//                List<Long> nearList = Arrays.asList(1L, 2L, 3L);
//                List<Long> alls = Arrays.asList(1L, 2L, 3L, 4L, 5L);
//
//                List<Long> yuIds = storeAllIds.stream().filter(x -> !nearStroeIds.contains(x)).collect(Collectors.toList());
//            }

//            if (nearStroeIds.size() > collect1.size()) {
//
//            }

//            stockInfoService.deleteStockInfoBathBySpuId(collect2, spuId);
        }


        //获取当前用户
        AdminUserRespDTO adminUserRespDTO = userUtils.getUser();

        // 执行最终的批量操作
        if (CollUtil.isNotEmpty(insertSkus)) {
            ProductSpuDO productSpuDO = productSpuService.getSpu(spuId);
            String spuCode = productSpuDO.getSpuCode().substring(3);
            insertSkus.forEach(productSkuCreateOrUpdateReqVO -> {
                ProductSkuDO productSkuDO = ProductSkuConvert.INSTANCE.convert(productSkuCreateOrUpdateReqVO);
                //生成skuCode
                String skuCode = autoCodeUtilsApi.getSpuAndSkuCode(spuCode);
                productSkuDO.setSkuCode(ConstantUtil.SKU+spuCode+skuCode);

                if(Objects.nonNull(adminUserRespDTO)){
                    productSkuDO.setCreator(adminUserRespDTO.getUsername());
                }

                productSkuMapper.insert(productSkuDO);


                // 插入门店信息到库存表中
                if (!CollectionUtil.isEmpty(nearStroeIds)) {
                    List<StockInfoSaveReqVO> list = new ArrayList<>();
                    nearStroeIds.forEach(x -> {
                        StockInfoSaveReqVO reqVO = new StockInfoSaveReqVO();
                        reqVO.setSkuId(productSkuDO.getId());
                        reqVO.setOwnerId(x);
                        reqVO.setOwnerType(1);
                        reqVO.setSpuId(spuId);

                    });
                    stockInfoService.createStockInfoBath(list);
                }
                //插入 sku和统一定价关系表
                createSkuOfferPriceRelation(productSkuDO.getId(),productSkuCreateOrUpdateReqVO);
            });
        }
        if (CollUtil.isNotEmpty(updateSkus)) {
            updateSkus.forEach(productSkuCreateOrUpdateReqVO -> {
                ProductSkuDO productSkuDO = ProductSkuConvert.INSTANCE.convert(productSkuCreateOrUpdateReqVO);
                if(Objects.nonNull(adminUserRespDTO)){
                    productSkuDO.setCreator(adminUserRespDTO.getUsername());
                }

                productSkuMapper.updateById(productSkuDO);
                //跟新 sku和统一定价关系表
                SkuOfferPriceRelationDO skuOfferPriceRelationDO = skuOfferPriceRelationService.getSkuOfferPriceRelationBySkuId(productSkuCreateOrUpdateReqVO.getId());
                skuOfferPriceRelationDO.setIncompletePrice(productSkuCreateOrUpdateReqVO.getIncompletePrice());
                skuOfferPriceRelationDO.setEnable(productSkuCreateOrUpdateReqVO.getEnable() != null ? productSkuCreateOrUpdateReqVO.getEnable():false);
                skuOfferPriceRelationDO.setPrice(productSkuCreateOrUpdateReqVO.getPrice());
                skuOfferPriceRelationService.updateSkuOfferPriceRelationById(skuOfferPriceRelationDO);
            });
        }
        if (CollUtil.isNotEmpty(existsSkuMap)) {
            productSkuMapper.deleteBatchIds(existsSkuMap.values());
            List<Long> list = new ArrayList<>(existsSkuMap.values());
            skuOfferPriceRelationService.updateSkuOfferPriceRelationByIds(list);
        }

    }

    public static void main(String[] args) {
        List<Long> nearList = Arrays.asList(1L, 2L, 6L, 7L);
        List<Long> alls = Arrays.asList(1L, 2L, 3L, 4L, 5L);

        List<Long> collect2 = nearList.stream().filter(x -> !alls.contains(x)).collect(Collectors.toList());
        System.out.println(collect2);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSkuStock(ProductSkuUpdateStockReqDTO updateStockReqDTO) {
        // 更新 SKU 库存
        updateStockReqDTO.getItems().forEach(item -> {
            if (item.getIncrCount() > 0) {
                productSkuMapper.updateStockIncr(item.getId(), item.getIncrCount());
            } else if (item.getIncrCount() < 0) {
                int updateStockIncr = productSkuMapper.updateStockDecr(item.getId(), item.getIncrCount());
                if (updateStockIncr == 0) {
                    throw exception(SKU_STOCK_NOT_ENOUGH);
                }
            }
        });

        // 更新 SPU 库存
        List<ProductSkuDO> skus = productSkuMapper.selectBatchIds(
                convertSet(updateStockReqDTO.getItems(), ProductSkuUpdateStockReqDTO.Item::getId));
        Map<Long, Integer> spuStockIncrCounts = ProductSkuConvert.INSTANCE.convertSpuStockMap(
                updateStockReqDTO.getItems(), skus);
        productSpuService.updateSpuStock(spuStockIncrCounts);
    }
}
